import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../models/dynamic_entity.dart';
import '../../api/dynamic_service.dart';
import '../../api/upload_service.dart';

class DynamicShareModel with ChangeNotifier {
  DynamicShareModel._privateConstructor();

  static final DynamicShareModel sharedDynamicModel =
      DynamicShareModel._privateConstructor();

  Map<String, Map<String, Object>> _formData = {
    'title': {
      'value': '',
      'controller': TextEditingController(),
      'obsecure': false,
      'icon': Icons.title,
      'hintText': '请输入标题',
    },
    'content': {
      'value': '',
      'controller': TextEditingController(),
      'obsecure': false,
      'icon': Icons.content_paste,
      'hintText': '请输入内容',
    },
  };
  Map<String, Map<String, Object>> get formData => _formData;

  File _imageFile;
  File get imageFile => _imageFile;

  DynamicEntity _currentDynamic;
  DynamicEntity get currentDynamic => _currentDynamic;

  clearState() {
    _currentDynamic = null;
    _imageFile = null;
    _formData.forEach((key, form) {
      form['value'] = '';
      (form['controller'] as TextEditingController)?.text = '';
    });
  }

  handleTextFieldChanged(String formKey, String value) {
    _formData[formKey]['value'] = value;
    notifyListeners();
  }

  handleClear(String formKey) {
    _formData[formKey]['value'] = '';
    (_formData[formKey]['controller'] as TextEditingController)?.clear();
    notifyListeners();
  }

  handleImagePicked(File imageFile) {
    _imageFile = imageFile;
    notifyListeners();
  }

  Future<bool> getDynamic(String id) async {
    EasyLoading.showInfo('加载中...', maskType: EasyLoadingMaskType.black);
    if (_currentDynamic?.id != id) {
      _currentDynamic = null;
    }
    var response = await DynamicService.get(id);
    if (response != null && response.statusCode == 200) {
      _currentDynamic = DynamicEntity.fromJson(response.data);
      _formData['title']['value'] = _currentDynamic.title;
      (_formData['title']['controller'] as TextEditingController).text =
          _currentDynamic.title;
      _formData['content']['value'] = _currentDynamic.content;
      (_formData['content']['controller'] as TextEditingController).text =
          _currentDynamic.content;
      notifyListeners();

      EasyLoading.dismiss();
      return true;
    } else {
      EasyLoading.showInfo(response?.statusMessage ?? '请求失败');
      return false;
    }
  }

  bool _validateForm({validateImage = false}) {
    if ((_formData['title']['value'] as String).trim() == '') {
      EasyLoading.showInfo('标题不能为空');
      return false;
    }

    if ((_formData['content']['value'] as String).trim() == '') {
      EasyLoading.showInfo('内容不能为空');
      return false;
    }

    if (validateImage) {
      if (_imageFile == null) {
        EasyLoading.showInfo('图片不能为空');
        return false;
      }
    }

    return true;
  }

  Future<bool> handleAdd() async {
    bool formValidated = _validateForm(validateImage: true);
    if (!formValidated) return false;

    EasyLoading.showInfo('请稍候...', maskType: EasyLoadingMaskType.black);
    String imageId;
    var imageResponse = await UploadService.uploadImage('image', _imageFile);
    if (imageResponse != null && imageResponse.statusCode == 200) {
      imageId = imageResponse.data['id'];
    }
    if (imageId == null) {
      EasyLoading.showInfo('图片上传失败');
      return false;
    }

    Map<String, String> newFormData = {};
    _formData.forEach((key, value) {
      newFormData[key] = value['value'];
    });
    newFormData['imageUrl'] = imageId;
    var response = await DynamicService.post(newFormData);
    if (response?.statusCode == 200) {
      EasyLoading.showSuccess('添加成功');
      _currentDynamic = DynamicEntity.fromJson(response.data);
      return true;
    } else {
      EasyLoading.showError(response?.statusMessage ?? '添加失败');
      return false;
    }
  }

  Future<bool> handleEdit() async {
    bool formValidated = _validateForm();
    if (!formValidated) return false;
    EasyLoading.showInfo('请稍候...', maskType: EasyLoadingMaskType.black);

    Map<String, String> newFormData = {};
    _formData.forEach((key, value) {
      newFormData[key] = value['value'];
    });
    if (_imageFile != null) {
      var imageResponse = await UploadService.uploadImage('image', _imageFile);
      if (imageResponse?.statusCode == 200) {
        newFormData['imageUrl'] = imageResponse.data['id'];
      } else {
        EasyLoading.showInfo('图片上传失败');
        return false;
      }
    }
    var response = await DynamicService.update(_currentDynamic.id, newFormData);
    if (response.statusCode == 200) {
      EasyLoading.showSuccess('保存成功');
      _currentDynamic.updateByJson(newFormData);
      return true;
    } else {
      EasyLoading.showError(response?.statusMessage ?? '保存失败');
      return false;
    }
  }
}
